// 引入express框架 搭建服务器
var app = require("express")();

var server = require("ws").Server;
var ws = new server(
  {
    port: 8888
  },
  () => {
    console.log("websocket服务运行中");
  }
);

// 引入并使用cors包 解决跨域
app.use(require("cors")());

// 引入并使用bodyParser包 解决不同格式的数据解析
const bodyParser = require("body-parser");
require("body-parser-xml")(bodyParser); // 解析 xml
app.use(bodyParser.json()); // 允许接收 JSON 格式的数据，前端使用 axios 包调用接口时使用 JSON
app.use(bodyParser.urlencoded({ extended: true })); // 接收 x-www 格式的数据，给 postman 测试 用的
app.use(bodyParser.xml());

// 引入 mysql
const mysql = require("mysql");
// 配置 mysql
let db = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "123456",
  database: "bishetantan",
  // 可以同时使用多条sql语句
  multipleStatements: true
});
// 连接 mysql
db.connect();

// 短信验证码
const Core = require("@alicloud/pop-core");
app.get("/api/v1/verification", (req, res) => {
  console.log(111);
  const phone = req.query.phone;
  const yzm =
    String(Math.floor(Math.random() * 10)) +
    String(Math.floor(Math.random() * 10)) +
    String(Math.floor(Math.random() * 10)) +
    String(Math.floor(Math.random() * 10)) +
    String(Math.floor(Math.random() * 10)) +
    String(Math.floor(Math.random() * 10));
  // var client = new Core({
  //   accessKeyId: "LTAI4FndAx6X1CHUfhk1oNus",
  //   accessKeySecret: "fk9kQDq7XvApxITrc6QfnVUcW8PVRR",
  //   endpoint: "https://dysmsapi.aliyuncs.com",
  //   apiVersion: "2017-05-25"
  // });
  // var params = {
  //   RegionId: "cn-hangzhou",
  //   PhoneNumbers: phone,
  //   SignName: "毕设探寻",
  //   TemplateCode: "SMS_184105594",
  //   TemplateParam: `{"code":${yzm}}`
  // };
  // var requestOption = {
  //   method: "POST"
  // };
  // client.request("SendSms", params, requestOption).then(
  //   result => {
  //     console.log(JSON.stringify(result));
  //     res.json({
  // code: 200,
  //       mag: "发送验证码成功",
  // phone,
  //       yzm
  //     });
  //   },
  //   ex => {
  //     console.log(ex);
  // res.json({
  //   code: 400,
  //   mag: "发送验证码失败"
  // });
  //   }
  // );
  if (phone.length == 11) {
    res.json({
      code: 200,
      mag: "发送验证码成功",
      phone,
      yzm
    });
  } else {
    res.json({
      code: 400,
      mag: "发送验证码失败"
    });
  }
});

// 获取地理位置
app.get("/api/v1/location", (req, res) => {
  let sql = `UPDATE register SET location_y = ${req.query.location_y}, location_x = ${req.query.location_x} WHERE id=${req.query.id}`;
  db.query(sql, (err, data) => {
    if (err) {
      // console.log(err);
      res.json({
        code: 400,
        msg: "定位失败",
        err
      });
    } else {
      res.json({
        code: 200,
        msg: "定位成功"
      });
    }
  });
  // console.log(req.query);
});

// 获取列表数据
app.get("/api/v1/getDataList", (req, res) => {
  let sql = `SELECT * FROM register where id != ${req.query.id}`;
  // console.log(req.query.id);
  db.query(sql, (err, data) => {
    if (data.length > 0) {
      // console.log(data);
      res.json({
        code: 200,
        msg: "获取信息成功",
        data
      });
    }
  });
});

// 获取匹配数据
app.get("/api/v1/pair", (req, res) => {
  let sql1 = `SELECT * FROM pair where user_id1 = ${req.query.id} OR user_id2 = ${req.query.id}`;
  // console.log(req.query.id);
  db.query(sql1, (err1, data1) => {
    // console.log(data1);
    arr = [];
    for (let i = 0; i < data1.length; i++) {
      // console.log(data1[i].user_id1, data1[i].user_id2);
      if (data1[i].user_id1 == req.query.id) {
        // console.log(data1[i].user_id2, 111);
        arr.push(data1[i].user_id2);
      } else {
        // console.log(222);
        arr.push(data1[i].user_id1);
      }
    }
    // console.log(arr);
    let sql2 = `SELECT id,username FROM register where id in (${arr})`;
    db.query(sql2, (err2, data2) => {
      // console.log(data2);
      res.json({
        code: 200,
        msg: "获取信息成功",
        data2
      });
    });
  });
});

// 登录
app.post("/api/v1/login", (req, res) => {
  // console.log(req.body.phone, req.body.pwd);
  let sql = `SELECT * FROM register WHERE phone = ${req.body.phone} AND password = ${req.body.pwd}`;
  db.query(sql, (err, data) => {
    if (err) {
      // console.log(err);
      res.json({
        code: 400,
        msg: "登录失败",
        err2
      });
    } else {
      if (data.length > 0) {
        // console.log(data);
        res.json({
          code: 200,
          msg: "登录成功",
          id: data[0].id
        });
      } else {
        res.json({
          code: 400,
          msg: "登录失败",
          err
        });
      }
    }
  });
});

// 注册
app.post("/api/v1/register", (req, res) => {
  let sql1 = `SELECT * FROM register WHERE phone = ${req.body.phone}`;
  let sql2 = `INSERT INTO register VALUES (null,${req.body.phone},'${req.body.pwd}',null,null,null)`;
  db.query(sql1, (err1, data1) => {
    if (data1.length > 0) {
      res.json({
        code: 300,
        msg: "该账号已存在",
        data1
      });
    } else {
      db.query(sql2, (err2, data2) => {
        if (err2) {
          console.log(err2);
          res.json({
            code: 400,
            msg: "注册失败",
            err2
          });
        } else {
          res.json({
            code: 200,
            msg: "注册成功"
          });
        }
      });
    }
  });
});

// 喜欢
app.post("/api/v1/like", (req, res) => {
  let sql1 = `SELECT * FROM likes WHERE user_id = ${req.body.likeId} AND like_id = ${req.body.userId}`;
  let sql2 = `INSERT INTO likes VALUES (null,${req.body.userId},${req.body.likeId})`;
  let sql3 = `INSERT INTO pair VALUES (null,${req.body.userId},${req.body.likeId})`;
  db.query(sql1, (err1, data1) => {
    // if (err1) return console.log(err1);
    // console.log(data1);
    if (data1.length > 0) {
      db.query(sql3, (err3, data3) => {
        // console.log("恭喜你们配对成功");
        res.json({
          code: 300,
          msg: "恭喜你们配对成功"
        });
      });
    } else {
      res.json({
        code: 200,
        msg: "成功喜欢对方"
      });
    }
  });
  db.query(sql2, (err2, data2) => {
    // console.log("成功喜欢对方");
  });
});

// 消息显示
app.get("/api/v1/msg", (req, res) => {
  console.log("111");
  let sql = `SELECT * FROM msg WHERE userId1 = ${req.query.userId1} or userId1 = ${req.query.userId2}`;
  db.query(sql, (err, data) => {
    console.log(err);
    let dataArr = [];
    let dataobj = {};
    for (let i = 0; i < data.length; i++) {
      dataobj = {
        type: data[i].type_id,
        msg: {
          id: data[i].id,
          type: data[i].type,
          time: data[i].time,
          userinfo: {
            uid: data[i].userId1
          },
          content: {
            text: data[i].text,
            url: data[i].url,
            length: data[i].length,
            w: data[i].width,
            h: data[i].height,
            blessing: data[i].bless,
            rid: data[i].rid,
            isReceived: false
          }
        }
      };
      if (dataobj.type == 0) {
        dataobj.type = "system";
      } else {
        dataobj.type = "user";
      }
      if (dataobj.msg.type == 0) {
        dataobj.msg.type = "text";
      } else if (dataobj.msg.type == 1) {
        dataobj.msg.type = "voice";
      } else if (dataobj.msg.type == 2) {
        dataobj.msg.type = "img";
      } else if (dataobj.msg.type == 3) {
        dataobj.msg.type = "redEnvelope";
      }
      // console.log(dataobj);
      dataArr.push(dataobj);
    }
    console.log(dataArr);
    res.json({
      code: 200,
      data: dataArr
    });
  });
});

let userArr = [];
ws.on("connection", function(socket) {
  socket.on("message", function(data) {
    console.log(data);
    console.log(data[0], data[1]);
    // data = data.split(",");
    userObj = {
      userId: data[0],
      socket
    };
    let userflog = false;
    if (userArr.length > 0) {
      for (let i = 0; i < userArr.length; i++) {
        if (userArr[i].userId == data[1]) {
          userArr[i].socket.send(data[0]);
        }
        if (userArr[i].userId == data[0]) {
          userflog = true;
        }
      }
      if (userflog != true) {
        userArr.push(userObj);
      }
    } else {
      userArr.push(userObj);
    }

    // console.log(data);
  });
});

// let clients = [];
// ws.on("connection", client => {
//   // console.log(client);
//   // clients.push(client);
//   // console.log(client);
//   client.send("欢迎光临");
//   client.on("message", msg => {
//     msgArr = msg.split(",");
//     chat_box = { user1: msgArr[0], user2: msgArr[1], client };

//     console.log(clients);
//     if (clients.length == 0) {
//       clients.push(chat_box);
//     } else {
//       for (let i = 0; i < clients.length; i++) {
//         if (msgArr[0] == clients[i].user1 && msgArr[1] == clients[i].user2) {
//         } else {
//           clients.push(chat_box);
//         }
//       }
//     }

//     // console.log(msg.handshake.query.user_id);
//     // msgArr = msg.split(",");
//     // for (let i = 0; i < msgArr.length; i++) {
//     //   if (msgArr[i] == "") {
//     //     msgArr[i] = null;
//     //   } else if (i != 1 && i != 2 && i != 7) {
//     //     msgArr[i] = Number(msgArr[i]);
//     //   }
//     // }
//     // let sql = `INSERT INTO msg VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?)`;
//     // db.query(sql, msgArr, (err, data) => {
//     //   console.log(err);
//     // });
//     // let sql2 = `SELECT id FROM msg`;
//     // db.query(sql2, msgArr, (err, data) => {
//     //   console.log(err);
//     //   client.send(data[data.length - 1].id); // 通过send方法来给前端发送消息
//     //   console.log(clients);
//     // });
//   });
//   client.on("close", msg => {
//     console.log("关闭服务器连接");
//   });
// });

// 发送消息
app.post("/api/v1/addMsg", (req, res) => {
  msgArr = req.body.msg;
  console.log(msgArr, "12131");

  let sql = `INSERT INTO msg VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?);SELECT * FROM msg`;
  db.query(sql, msgArr, (err, data) => {
    if (err) console.log(err);
    // console.log(data[1][data[1].length - 1]);
    res.json({
      code: 200,
      data: data[1][data[1].length - 1]
    });
  });
});

// // 建立webswocket
// app.get("echo", (req, res) => {
//   var ws = require("nodejs-websocket");
//   console.log("开始建立连接...");
//   var server = ws
//     .createServer(function(conn) {
//       conn.on("text", function(str) {
//         console.log("收到的信息为:" + str); /*
//           conn.sendText(str)*/
//         //回调
//         var backStr = "get the str";
//         conn.send(JSON.stringify(backStr));
//         console.log("发送回调信息");
//       });
//       conn.on("close", function(code, reason) {
//         console.log("关闭连接");
//       });
//       conn.on("error", function(code, reason) {
//         console.log("异常关闭");
//       });
//     })
//     .listen(8081, () => {
//       console.log("WebSocket建立完毕");
//     });
// });

app.listen(8080, () => console.log("http://192.168.1.4:8080"));
